<?php

namespace App\Kuafu\Mybank\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\Shop\Model\Shop;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasOne;

class MybankWalletRecordModel extends BaseModel
{
    use HasFactory, KfSoftDeletes, KfUid;

    protected $connection = 'mysql';
    protected $table      = "mybank_wallet_record";

    protected $fillable = [
        'id',
        'shopId',
        'merchantId',
        'transId',
        'transDate',
        'status',
        'transType',
        'isShow',
        'displayTransType',
        'transDesc',
        'transAmount',
        'afterRemainingAmount',
        'updatedAt',
        'createdAt',
        'remark',
        'isDeleted',
        'supplyChainBalance',
        'createdByUid',
        'updatedByUid',
        'recordIdType',
        'platformType',
        'walletRecordType',
        'recordId',
    ];

    const INCOME_TRANS_TYPE   = 1;
    const PAY_TRANS_TYPE      = 2;
    const RECHARGE_TRANS_TYPE = 3;
    const EARNING_TRANS_TYPE  = 4;

    const MAPPING_TRANS_TYPE = [
        self::INCOME_TRANS_TYPE   => '网商提现',
        self::PAY_TRANS_TYPE      => '支出',
        self::RECHARGE_TRANS_TYPE => '网商充值',
        self::EARNING_TRANS_TYPE  => '收入',
    ];

    const MAPPING_TRANS_TYPE_PLUS_MINUS = [
        self::INCOME_TRANS_TYPE   => '-',
        self::PAY_TRANS_TYPE      => '-',
        self::EARNING_TRANS_TYPE  => '+',
        self::RECHARGE_TRANS_TYPE => '+',
    ];

    const HIDE_RECORD = 0;
    const SHOW_RECORD = 1;

    const MAPPING_IS_SHOW_RECORD = [
        self::HIDE_RECORD => '隐藏',
        self::SHOW_RECORD => '显示',
    ];

    const DEFAULT_STATUS = 0;
    const SUCCESS_STATUS = 1;
    const ERR_STATUS     = 2;

    const MAPPING_TRANS_STATUS = [
        self::DEFAULT_STATUS => '已提交申请',
        self::SUCCESS_STATUS => '成功',
        self::ERR_STATUS     => '失败',
    ];

    // 平台类型
    const PLATFORM_TYPE_DEFAULT   = 0;
    const PLATFORM_TYPE_MYBANK    = 1;
    const PLATFORM_TYPE_KUAFU_POS = 2;
    const PLATFORM_TYPE_ELE       = 3;
    const PLATFORM_TYPE_MEITUAN   = 4;

    const PLATFORM_TYPE_TEXT = [
        self::PLATFORM_TYPE_DEFAULT   => '系统',
        self::PLATFORM_TYPE_MYBANK    => '网商',
        self::PLATFORM_TYPE_KUAFU_POS => '夸父收银',
        self::PLATFORM_TYPE_ELE       => '饿了么',
        self::PLATFORM_TYPE_MEITUAN   => '美团',
    ];

    const RECORD_ID_TYPE_WITHHOLD       = 1; // 协议代扣ID
    const RECORD_ID_TYPE_UNFREEZE       = 2; // 余额解冻记录 ID - 暂时没用
    const RECORD_ID_TYPE_BILL_RECORD_ID = 3; // 批次处理 ID
    const RECORD_ID_TYPE_VOSTRO_BILL    = 4; // 网商订单记录 ID
    const RECORD_ID_TYPE_REFUND         = 5; // 退款记录 ID
    const RECORD_ID_TYPE_CASHIER_PAY    = 6; // 网商小程序支付-收银台

    /**
     * @return HasOne
     */
    public function shopRel(): HasOne
    {
        return $this->hasOne(Shop::class, "id", "shopId");
    }

    /**
     * @return HasOne
     */
    public function mybankEntryRel(): HasOne
    {
        return $this->hasOne(MybankEntryModel::class, "merchantId", "merchantId");
    }


    /**
     * @param string $startDate
     * @param string $endDate
     * @param int $transType
     * @param array $shopIds
     * @param string $merchantId
     * @param array $merchantIds
     * @param array $transTypes
     * @param int $isShow
     * @params array $walletRecordType
     * @return int|mixed
     */
    public static function getSumAmount(
        string $startDate,
        string $endDate,
        int $transType,
        array $shopIds,
        string $merchantId = '',
        array $merchantIds = [],
        array $transTypes = [],
        int $isShow = 0,
        array $walletRecordType = []
    ): int {
        return self::query()
                   ->when($shopIds && is_array($shopIds), function ($query) use ($shopIds) {
                       $query->whereIn('shopId', $shopIds);
                   })
                   ->when($merchantId, function ($query) use ($merchantId) {
                       $query->where('merchantId', $merchantId);
                   })
                   ->when($merchantIds, function ($query) use ($merchantIds) {
                       $query->whereIn('merchantId', $merchantIds);
                   })
                   ->when($startDate && $endDate, function ($query) use ($startDate, $endDate) {
                       $query->whereBetween('transDate', [strtotime($startDate), strtotime($endDate) + 86400]);
                   })
                   ->when($transType && !$transTypes, function ($query) use ($transType) {
                       $query->where('transType', $transType);
                   })
                   ->when(!$transType && $transTypes, function ($query) use ($transTypes) {
                       $query->whereIn('transType', $transTypes);
                   })
                   ->when($isShow > 0, function ($query) use ($isShow) {
                       $query->where('isShow', $isShow);
                   })
                   ->when($walletRecordType , function ($query) use ($walletRecordType) {
                       $query->whereIn('walletRecordType', $walletRecordType);
                   })
                   ->sum('transAmount');
    }

    /**
     * 通过商户号查询余额
     * @param string $merchantId
     * @return string
     */
    public static function getBalance(string $merchantId): string
    {
        $afterRemainingAmount = self::query()
                                    ->where(['merchantId' => $merchantId])
                                    ->where('isShow', self::SHOW_RECORD)
                                    ->orderByDesc('transDate')
                                    ->value('afterRemainingAmount');
        return $afterRemainingAmount ? bcdiv100($afterRemainingAmount) : 0;
    }
}
